package com.srlg.common.util.crypto.impl;

import com.srlg.common.anno.EncryptTransaction;
import com.srlg.common.util.crypto.DBAESUtil;
import com.srlg.common.util.crypto.IDecryptUtil;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * @desc:
 * @author: srlg li
 * @date: 2023/2/2 10:43
 */
@Component
public class DecryptUtilImpl implements IDecryptUtil {

    /**
     * 解密
     * @param result resultType的实例
     * @return
     * @param <T>
     * @throws IllegalAccessException
     */
    @Override
    public <T> T decrypt(T result) throws IllegalAccessException {

        // 取出resultType的类
        Class<?> retCls = result.getClass();
        Field[] declaredFields = retCls.getDeclaredFields();

        for (Field field : declaredFields) {
            // 筛选 被注解DecryptTransaction标记的字段

            EncryptTransaction encryptTransaction = field.getAnnotation(EncryptTransaction.class);

            if (!Objects.isNull(encryptTransaction)) {
                field.setAccessible(true);
                Object o = field.get(result);
                // String 加密
                if (o instanceof String) {
                    String value = (String) o;

                    // 对注解字段进行逐一解密
                    try {
                        field.set(result, DBAESUtil.decrypt(value));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return result;
    }
}
